package com.platform.qujia.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.platform.qujia.controller.CouponController;
import com.platform.qujia.dao.AppUserInfoMapper;
import com.platform.qujia.dao.CustomerCardSettingMapper;
import com.platform.qujia.enums.UserSourceEnum;
import com.platform.qujia.pojo.AppUserInfo;
import com.platform.qujia.pojo.AppUserInfoExample;
import com.platform.qujia.pojo.CustomerCardSetting;
import com.platform.qujia.pojo.Enterprise;
import com.platform.qujia.pojo.vo.UserInfoVo;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.MobilePhoneUtil;
import com.platform.qujia.utils.redis.RedisCacheUtil;
import com.platform.qujia.utils.yunHua.yunHuaPayUtils;
import com.yunhua.oil.common.core.utils.LocalDateUtils;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service("appUserInfoService")
@Slf4j
public class AppUserInfoServiceImpl implements AppUserInfoService {


    @Resource
    private AppUserInfoMapper appUserInfoMapper;
    @Autowired
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private CustomerCardSettingMapper customerCardSettingMapper;


    @Resource
    private AppUserSyncService appUserSyncService;

    @Resource
    private RedisCacheUtil redisCacheUtil;

    private static final String MEMBER_CODE = "member-code";

    @Override
    public void increaseShareCount(Long userId) {
        appUserInfoMapper.increaseShareCount(userId);
    }

    @Override
    public Integer getShareCountByUserId(Long userId) {
        return appUserInfoMapper.getShareCountByUserId(userId);
    }


    //根据用户memberCode获取用户信息
    @Override
    public AppUserInfo getAppUserInfoByMemberCode(AppUserInfo appUserInfo) {
        return appUserInfoMapper.getAppUserInfoByMemberCode(appUserInfo);
    }

    //更新客户积分
    @Override
    public void updateAppUserIntegral(AppUserInfo appUserInfo) {
        appUserInfoMapper.updateAppUserIntegral(appUserInfo);
    }

    //获取用户信息和余额
    @Override
    public AppUserInfo getAppUserInfoAndBalance(AppUserInfo appUserInfo) {
        AppUserInfo userInfo = appUserInfoMapper.getAppUserInfoAndBalance(appUserInfo);
        if (userInfo != null) {
            CustomerCardSetting cardSetting = new CustomerCardSetting();
            cardSetting.setEnterpriseId(userInfo.getStationId());
            CustomerCardSetting setting = customerCardSettingMapper.getOneJoinEnterprise(cardSetting);
            if (setting == null || !StringUtils.equals("1",setting.getCardEnabledFlag()) || StringUtils.isBlank(setting.getCardOilsType())) {
                userInfo.setBalance(BigDecimal.ZERO);
            }else{
                BigDecimal balance = electronicMembershipCardService.getCustomerElectronicCardBalance(userInfo.getMobilePhone(),
                        setting.getEnterpriseId(),
                        StringUtils.equals("1",setting.getCardUseRangeFlag()),
                        Arrays.asList(setting.getCardOilsType().split(",")));
                userInfo.setBalance(balance);
            }
        }
        return userInfo;
    }

    //根据手机号和油站获取用户信息
    @Override
    public List<AppUserInfo> selectAppUserInfoByMobilePhoneAndStationId(AppUserInfo appUserInfo) {
        return appUserInfoMapper.selectAppUserInfoByMobilePhoneAndStationId(appUserInfo);
    }

    //获取用户信息
    @Override
    public AppUserInfo getAppUserInfo(AppUserInfo appUserInfo) {
        return appUserInfoMapper.getAppUserInfo(appUserInfo);
    }

    //获取用户信息
    @Override
    public List<String> checkUserCoupon(AppUserInfo appUserInfo) {
        return appUserInfoMapper.checkUserCoupon(appUserInfo);
    }

    //新增用户信息
    @Override
    @Transactional
    public void addAppUserInfo(AppUserInfo appUserInfo) {
        // 统一生成会员编码
        String time = LocalDateUtils.format(LocalDate.now(), "yyMMdd");
        String redisKey = time + MEMBER_CODE;
        Integer value = redisCacheUtil.getCacheObject(redisKey);
        if(Objects.isNull(value)){
            redisCacheUtil.setCacheObject(redisKey,0,25, TimeUnit.HOURS);
        }
        //每次自增1
        Long increment = redisCacheUtil.getIncrement(redisKey, 1);
        String memberCode = String.format("%06d", increment);
        appUserInfo.setMemberCode(time + memberCode);
        appUserInfo.setUserSource(UserSourceEnum.SELF.getValue());
        appUserInfoMapper.addAppUserInfo(appUserInfo);
        //更新yunhuaUserId
        appUserSyncService.syncUser(appUserInfo.getMobilePhone());

      }


    //更新unionID
    @Override
    public void updateAppUserInfo(AppUserInfo appUserInfo) {
        appUserInfoMapper.updateAppUserInfo(appUserInfo);
    }

    @Override
    public void updateAppUserInfoByBlogOpenid(AppUserInfo appUserInfo) {
        appUserInfoMapper.updateAppUserInfoByBlogOpenid(appUserInfo);
    }

    @Override
    public void updateAppUserInfoByUnionId(AppUserInfo appUserInfo) {
        appUserInfoMapper.updateAppUserInfoByUnionId(appUserInfo);
    }

    @Override
    public void updateAppUserInfoByUserId(AppUserInfo appUserInfo){
        appUserInfoMapper.updateAppUserInfoByUserId(appUserInfo);
    }



    //判断使用小程序支付的用户是否关注公众号
    @Override
    public String whetherFollowGzh(Map map) {
        return appUserInfoMapper.whetherFollowGzh(map);
    }

    @Override
    public List<AppUserInfo> selectAppUserInfoByStationId(Long stationId) {
        return appUserInfoMapper.selectAppUserInfoByStationId(stationId);
    }

    public AppUserInfo getById(Integer id){
        return appUserInfoMapper.getById(id);
    }

    public AppUserInfo getAppUserById(Long appUserId){
        return appUserInfoMapper.getAppUserById(appUserId);
    }


    public UserInfoVo getOrCreateUserInfo(String openId, String nickName, Integer enterpriseId){
        AppUserInfo userInfo = new AppUserInfo();
        userInfo.setBlogOpenid(openId);
        userInfo.setStationId(enterpriseId);
        AppUserInfo info = appUserInfoMapper.getAppUserInfo(userInfo);
        if (info == null) {
            /*String format = new SimpleDateFormat("yyMMdd").format(new Date()) + RandomStringUtils.randomNumeric(5);
            userInfo.setMemberCode(format);*/
            userInfo.setNickName(nickName);
            userInfo.setMobilePhone(MobilePhoneUtil.generateFakePhone());
            userInfo.setRegisteDate(new Date());
            userInfo.setIntegral(0);
            userInfo.setGrowUpValue(0);
            userInfo.setFollowStatus("1");
            userInfo.setUserSource(UserSourceEnum.SELF.getValue());
            appUserInfoMapper.addAppUserInfo(userInfo);
            info = userInfo;
            info.setMobilePhone(null);
        }
        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);
        UserInfoVo vo = new UserInfoVo();
        vo.setConsumerId(info.getUserId());
        //vo.setMobilePhone(info.getMobilePhone());
        vo.setNickName(info.getNickName());
        vo.setEnterprise(enterprise);
        return vo;
    }

    @Override
    public int deleteUserInfoById(Integer id) {
        return appUserInfoMapper.deleteUserInfoById(id);
    }

    @Override
    public int updateById(AppUserInfo appUserInfo) {
        return appUserInfoMapper.updateById(appUserInfo);
    }

    @Override
    public AppUserInfo selectAppUserInfoById(Long userId) {
        return appUserInfoMapper.selectAppUserInfoById(userId);
    }

    @Override
    public int countByExample(AppUserInfo appUserInfo) {
        return appUserInfoMapper.countByExample(appUserInfo);
    }

    @Override
    public List<AppUserInfo> queryPageByExample(AppUserInfo userInfo, int offset, int limit) {
        return appUserInfoMapper.queryPageByExample(userInfo,offset,limit);
    }

    @Override
    public void updateWxBonusSynByUserId(AppUserInfo appUserInfo) {
        appUserInfoMapper.updateWxBonusSynByUserId(appUserInfo);
    }
}
